package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Override
    public R submit(Orders orders) {
        //订单与订单明细为一对多
        //orders包含addressBookId，
        //A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            return R.error("购物车为空，不能下单");
        }

        //查询用户数据
        User user = userService.getById(userId);

        //C. 根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            return R.error("请选择地址");
        }

        //D. 封装订单数据，存储
        long orderId = IdWorker.getId();//订单号，雪花算法
        //存储订单的总金额
        AtomicInteger amount = new AtomicInteger(0);

        //封装
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);

        //E. 封装订单明细数据
        //shoppingcarts==orderdetail
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetails);
        //F. 清空
        shoppingCartService.remove(wrapper);
        return R.success("下单成功");

    }

    @Override
    public R findByPageAndCondition(Integer page, Integer pageSize, Integer number, String beginTime, String endTime) {
        IPage<Orders> pageinfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        if(number!=null){
            wrapper.eq(Orders::getNumber,number);
        }
        if(beginTime!=null&&beginTime!=""&&endTime!=null&&endTime!=""){
            wrapper.gt(Orders::getOrderTime,beginTime)
                    .lt(Orders::getOrderTime,endTime);
        }
        IPage<Orders> page1 = this.page(pageinfo, wrapper);

        return R.success(page1);
    }


    @Override
    public R findByPage(Integer page, Integer pageSize) {
        //获取orders
        IPage<Orders> ipage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> qwrapper=new LambdaQueryWrapper<>();
        qwrapper.orderByDesc(Orders::getOrderTime);
        IPage<Orders> page1 = this.page(ipage,qwrapper);
        List<Orders> orders = page1.getRecords();
        //新建ordersdto,封装
        List<OrdersDto> ordersDtos=new ArrayList<>();
        for (Orders order : orders) {
            OrdersDto ordersDto=new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);
            //获取orderdetail
            LambdaQueryWrapper<OrderDetail> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
            //
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }
        //返回查询到的集合
        Page<OrdersDto> page2=new Page<>(page,pageSize);
        //Page<OrdersDto> page2=new Page<>();
        BeanUtils.copyProperties(page1,page2,"records");
        page2.setRecords(ordersDtos);
        //page2.setTotal(page1.getTotal());

        return R.success(page2);
    }


}